package com.xhsj.user.event.listener;


import com.xhsj.user.event.event.MessageEvent;
import com.xhsj.user.hr.process.message.entity.TbProjectMessage;
import com.xhsj.user.hr.process.message.service.TbProjectMessageService;
import com.xhsj.user.hr.system.entity.TbGlobalUser;
import com.xhsj.user.hr.system.mapper.TbGlobalUserMapper;
import com.xhsj.user.hr.system.service.TbGlobalUserService;
import com.xhsj.user.utils.IdGen;
import com.xhsj.user.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * 消息监听
 * @author suxiaolin
 * @date 2020/4/1 9:24
 */
@Slf4j
@Component
public class MessageListener {
    @Value("${spring.profiles.active}")
    private String profiles;
    @Autowired
    private TbProjectMessageService tbProjectMessageService;

    @Autowired
    private TbGlobalUserService tbGlobalUserService;

    @Autowired
    private TbGlobalUserMapper tbGlobalUserMapper;

    /**
     * 注册监听实现方法
     */
    @EventListener
    public void register(MessageEvent messageEvent) {
        Map<String, Object> msg = messageEvent.getMsg();
        TbProjectMessage tbProjectMessage = StringUtils.toJavaBean(msg, TbProjectMessage.class);
        if(tbProjectMessage.getProjectId()==1){
            registerPatent(messageEvent);
        }else{

            List<Object> userIds = (List<Object>) msg.get("userIds");
            for (Object userId : userIds) {
                String phoneNumber = tbGlobalUserMapper.getPhoneNumberById(StringUtils.toLong(userId));
                if (StringUtils.isNotBlank(phoneNumber)) {
                    tbProjectMessage.setRecipient(userId.toString());
                    String uuid = IdGen.uuid();
                    tbProjectMessage.setId(uuid);
                    tbProjectMessage.setCreateDate(new Date());
                    tbProjectMessage.setUpdateDate(new Date());
                    if (!"0".equals(tbProjectMessage.getDataId())) {
                        tbProjectMessageService.save(tbProjectMessage);
                    }

                    CompletableFuture.runAsync(() -> {
                        if ("pro".equals(profiles)) {
                            tbProjectMessageService.sendMessage(phoneNumber, tbProjectMessage.getTitle(), 1,String.valueOf(msg.get("name")));
                        } else {
                            tbProjectMessageService.sendMessage("12345678910", tbProjectMessage.getTitle(), 1,String.valueOf(msg.get("name")));
                        }
                    });
                    log.info("msg,{}",msg);
                }

            }
        }
    }

    /**
     * 专利注册监听实现方法
     */

    public void registerPatent(MessageEvent messageEvent) {
        try {
            Map<String, Object> msg = messageEvent.getMsg();
            TbProjectMessage tbProjectMessage = StringUtils.toJavaBean(msg, TbProjectMessage.class);
            List<String> recipientList = Arrays.asList(tbProjectMessage.getRecipient().split(","));

            for (String recipient : recipientList) {
                tbProjectMessage.setRecipient(recipient);
                tbProjectMessage.setId(IdGen.uuid());
                    boolean save = tbProjectMessageService.save(tbProjectMessage);
                    log.error("消息保存到数据库信息{}", save);
            }

            // 判断是否发送  状态 0 未读 1 已读 2未发送
            if (tbProjectMessage.getStatus() !=2 ) {
                List<TbGlobalUser> byId = tbGlobalUserMapper.getByIds(recipientList);
                for (TbGlobalUser user:byId) {
                    if(!StringUtils.isBlank(user.getPhoneNumber())) {
                        CompletableFuture<Void> f = CompletableFuture.runAsync(() -> {
                            if ("pro".equals(profiles)) {
                                tbProjectMessageService.sendMessage(user.getPhoneNumber(), "专利管理", 1,"");
                            }else{
                                System.err.println("消息发送");
                                tbProjectMessageService.sendMessage("188011353871","专利管理",1,"");
                            }
                        });
                    }
                }
            }

        }catch (Exception e){
            log.error("消息保存到数据库错误",e);
        }
    }
}
